<template>
  <div class="message">
    <div class="listcontent">
      <div class="list_item flex_box" v-for="item in userList" :key='item.userId' @click="userChange(item)">
        <el-image style="width: 40px; height: 40px;" :src="item.avatar" fit="fill" class="avatar"></el-image>
        <div class="flex1">
          <span class="name">{{item.userName}}</span>
          <p class="msg_text">{{item.content}}</p>
        </div>
      </div>
    </div>
    <div class="maincontent">
      <div class="chatinfo">
        <el-image style="width: 36px; height: 36px;" :src="chatInfo.avatar" fit="fill" class="avatar"></el-image>
        <div class="flex1">
          <span class="name">{{chatInfo.userName}}</span>
          <p class="msg_text">{{chatInfo.info}}</p>
        </div>
        <el-tooltip class="item" effect="dark" content="文件" placement="bottom">
          <span class="iconfont icon-wenjianjia" @click="showFile"></span>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="聊天记录" placement="bottom">
          <span class="iconfont icon-xiaoxi" @click="chatRecord"></span>
        </el-tooltip>
        
      </div>
      <div class="msgcontainer">
        <p v-show="listLoading" class="loading">加载中...</p>
        <div class="chat_item" v-for="(item,index) in list" :key='item.id'>
            <p class="starttime">{{getMsgTime(item.time,index)}}</p>
            <div class="chat_item_info" :class="item.userId==userInfo.userId?'right':'left'">
                <el-image style="width: 36px; height: 36px;" v-if="item.avatar" :src="item.avatar" fit="fill" class="avatar"></el-image>
                <p class="avatar" v-else>{{getImg(item.userName)}}</p>
                <div class="chat_item_con">
                    <div class="content" v-if="item.contentType=='text'">{{item.content}}</div>
                    <div class="content" v-else-if="item.contentType=='image'">
                        <img :src="item.content" alt="" class="chat_img">
                    </div>
                    <div class="content file_content" v-else-if="item.contentType=='file'" @click="downFile(item)">
                        <p>{{item.content}}</p>
                        <img src="@/assets/images/file.png" class="file_icon" alt="">
                    </div>
                </div>
            </div>
        </div>
      </div>
      <div class="chat_bottom">
        <div class="img_box" v-loading="uploadLoading">
          <!-- <span class="iconfont icon-biaoqing_xiao_o" title="表情"></span> -->
          <el-upload
            class="upload-demo"
            action=''
            :http-request='uploadRequestImg'
            :on-change="uploadChange"
            accept='.jpg,.png,.jpeg'
            :show-file-list="false">
            <el-tooltip class="item" effect="dark" content="上传图片" placement="bottom">
              <span class="iconfont icon-tupian"></span>
            </el-tooltip>
          </el-upload>
          <el-upload
            class="upload-demo"
            action=""
            :http-request='uploadRequestDoc'
            :on-change="uploadChange"
            accept='.doc,.pdf,.docx'
            :show-file-list="false">
            <el-tooltip class="item" effect="dark" content="上传文件" placement="bottom">
              <span class="iconfont icon-wenjianjia"></span>
            </el-tooltip>
          </el-upload>
          <el-tooltip class="item" effect="dark" content="语音/视频通话" placement="bottom">
            <span class="iconfont icon-shipin" @click="conversation"></span>
          </el-tooltip>
          <!-- <div class="smile_box" v-show="smileShow">
            <img src="@/assets/images/avatar.jpg" alt="" v-for="(item,index) in 10" :key="index">
          </div> -->
        </div>
        <textarea v-model="con" class="textarea"></textarea>
        <div class="btn_box">
          <p class="btn" @click="sendText">发送</p>
        </div>
      </div>
    </div>
    <fileList ref="fileList"></fileList>
    <el-dialog
      title="语音视频通话"
      :visible.sync="videoShow"
      width="40%">
      <div style="width:100%;height:300px">
        <iframe 
          allow="camera; microphone; fullscreen; display-capture; autoplay" 
          src="https://uc.cadreman.com/101123?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb250ZXh0Ijp7InVzZXIiOnsiYXZhdGFyIjoiaHR0cHM6L2dyYXZhdGFyLmNvbS9hdmF0YXIvYWJjMTIzIiwibmFtZSI6IkpvaG4gRG9lIiwiZW1haWwiOiJqZG9lQGV4YW1wbGUuY29tIiwiaWQiOiJhYmNkOmExYjJjMy1kNGU1ZjYtMGFiYzEtMjNkZS1hYmNkZWYwMWZlZGNiYSJ9LCJncm91cCI6ImExMjMtMTIzLTQ1Ni03ODkifSwiYXVkIjoidWMiLCJpc3MiOiJ1YyIsInN1YiI6InVjLmNhZHJlbWFuLmNvbSIsInJvb20iOiIqIiwiZXhwIjoxNjM4NTkxODQzNTYyfQ.JFyHYbtlbEAeZa7xTYocmJW_2KwjNy4rVhatg-oJLrw" 
          style="height: 100%; width: 100%; border: 0px;">
        </iframe>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="videoShow = false">取 消</el-button>
        <el-button type="primary" @click="videoShow = false">确 定</el-button>
      </span>
    </el-dialog>
    <record ref="record"></record>
  </div>
</template>
<script>
import {addZero} from '@/utils/index.js'
import fileList from '@/components/fileList'
import record from '@/components/record'
export default {
  components:{
    record,
    fileList,
  },
  data() {
    return {
      chatInfo:{
        avatar:require('@/assets/images/avatar.jpg'),// 测试头像地址
        userName:'宋春波',
        info:'宋春波（卡德曼信息技术 | 研发工程师）',
        userId:2
      },// 当前对话用户信息
      userInfo:{
        avatar:'',// 测试头像地址
        userName:'曹丽丽',
        userId:1
      },// 当前登录人信息
      userList:[
        {
          userId:2,
          avatar:require('@/assets/images/avatar.jpg'),
          content:'嗯嗯',
          userName:'宋春波',
          info:'宋春波（卡德曼信息技术 | 研发工程师）',
        },
        {
          userId:3,
          avatar:require('@/assets/images/avatar.jpg'),
          content:'哈哈',
          userName:'晓燕',
          info:'晓燕（卡德曼信息技术 | 研发工程师）',
        }
      ], // 左侧消息列表
      listLoading:false, // 加载更多状态
      smileShow:false,// 表情图标的显示和隐藏
      videoShow:false,// 语音视频通话
      list:[
        {
          id:1,
          userId:1,
          avatar:'',
          content:'哈哈',
          userName:'曹丽丽',
          contentType:'text',
          time:'2021-12-05 09:00:00'
        },
        {
          id:2,
          userId:2,
          avatar:require('@/assets/images/avatar.jpg'),
          content:'嗯嗯',
          userName:'宋春波',
          contentType:'text',
          time:'2021-12-06 09:00:00'
        },
      ],// 聊天记录
      uploadLoading:false, // 上传文件，图片，视频状态
      con:'',// 输入内容
      kg:true,// 发送内容开关
      dom:'', // 聊天记录内容盒子
      scrollHeight:'',// 元素实际高度
    }
  },
  mounted() {
    this.dom = document.querySelector('.msgcontainer')
  },
  methods:{
    // 消息列表切换
    userChange(item) {
      this.chatInfo = {...item}
      this.list = []
    },
    // 发送消息
    sendText() {
      if (!this.kg) return
      let con = this.con
      if (con == ''){
        
      } else {
        this.kg = false;
        this.sendMsg(con,'text')
      }
    },
    // 上传图片
    uploadRequestImg(file) {
      this.sendMsg(URL.createObjectURL(file.file),'image')
    },
    // 上传文件
    uploadRequestDoc(file) {
      this.sendMsg(URL.createObjectURL(file.file),'file')
    },
    // 发送消息
    sendMsg(con,type) {
      this.list.push({
        id:this.list.length+1,
        userId:this.userInfo.userId,
        avatar:'',
        content:con,
        userName:this.userInfo.userName,
        contentType:type,
        time:this.getTime()
      })
      this.kg = true
      this.con = ''
      this.uploadLoading = false
      this.scrollToBottom()
    },
    scrollToBottom() {
      this.$nextTick(()=>{
        this.getImgLoadEd(()=>{
          setTimeout(()=>{
            this.dom.scrollTop = this.dom.scrollHeight
          },100)
        })
      })
    },
    getImgLoadEd(callback) {
        // 查询容器下所有图片
        let images = document.querySelectorAll('.chat_img')
        if (images.length == 0) {
          callback && callback();
          return
        }
        // Array.prototype.slice.call将images类数组转换成合法数组
        const promises = Array.prototype.slice.call(images).map(node => {
            return new Promise((resolve, reject) => {
                let loadImg = new Image();
                loadImg.src = node.src;
                loadImg.onload = () => {
                    resolve(node);
                }
                loadImg.complete = ()=>{
                    resolve(node);
                }
            });
        });
        // 利用Promise.all监听所有图片加载完成
        Promise.all(promises).then(results => {
            callback && callback();
        }).catch(e => {
            callback && callback();
        })
    },
    // 打开文件
    showFile() {
      this.$refs.fileList.show()
    },
    chatRecord() {
      this.$refs.record.show()
    },
    // 语音视频通话
    conversation() {
      this.videoShow = true
    },
    //  获取当前时间
    getTime() {
      let date =  new Date()
      let year = addZero(date.getFullYear())
      let month = addZero(date.getMonth()+1)
      let day = addZero(date.getDate())
      let hour = addZero(date.getHours())
      let minute = addZero(date.getMinutes())
      let second = addZero(date.getSeconds())
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`
    },
    // 上传状态监听
    uploadChange(file, fileList) {
      if (file.status == 'ready') {
        //开启loading效果
        this.uploadLoading = true;
      } else {
        this.uploadLoading = false;
      }
    },
    //根据两个时间对比判断是否显示时间
    getMsgTime(time,index){
      time = new Date(time).getTime()
      if (index == 0) return this.getTimeDate(time)
      let time1 = this.list[index-1].time
      time1 = new Date(time1).getTime()
      if (time - time1 > 5*60*1000) return this.getTimeDate(time)
    },
    // 如果没有头像，截取姓名后两位
    getImg(name) {
      let len = name.length
      if(len <= 2) {
        return name
      } else {
        return name.slice(len-2)
      }
    },
    // 根据时间戳转日期
    getTimeDate(shijianchuo) {
      var time = new Date(shijianchuo);
      var y = time.getFullYear();
      var m = time.getMonth()+1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      var time1 = new Date()
      var y1 = time1.getFullYear();
      var m1 = time1.getMonth()+1;
      var d1 = time1.getDate();
      if (y1 - y >= 1) {
          return y+'年'+addZero(m)+'月'+addZero(d)+'日 '+addZero(h)+':'+addZero(mm);
      } else if (m1 - m >= 1 || d1 - d > 1) {
        let am = ''
        if (h < 12) {
            am = '上午'
        } else if (h < 18) {
            am = '下午'
        } else {
            am = '晚上'
        }
        return addZero(m)+'月'+addZero(d)+'日 '+am+addZero(h)+':'+addZero(mm);
      } else if (d1 - d == 1) {
          return '昨天 '+addZero(h)+':'+addZero(mm);
      } else {
        return addZero(h)+':'+addZero(mm);
      }
    },
  }
}
</script>
<style lang='stylus' scoped>
@import '~@/assets/stylus/variable'
.message
  height: 100%
  display flex
  position relative
  .listcontent
    width: 276px
    flex-shrink: 0;
    box-shadow 3px 0 6px #d7d5d5
    padding 5px
    box-sizing border-box
    .list_item
      padding 10px
      cursor pointer
      border-radius: 4px
      &:hover
        background #f4f4f4
      .avatar
        margin-right:10px
        border-radius: 4px
      .name
        font-size 14px
        line-height 20px
        color #222
      .msg_text
        color #999
        font-size 12px
        line-height 20px
        text-overflow: ellipsis
        overflow: hidden
        white-space: nowrap
  .maincontent
    flex: 1;
    overflow: hidden;
    border-radius: 0 4px 4px 0;
    background #f4f4f4
    .chatinfo
      display: flex;
      align-items: center;
      height: 56px;
      background: #fcfcfc;
      padding 0 10px
      .avatar
        margin-right:10px
        border-radius: 4px
      .name
        font-size 14px
        line-height 20px
        color #222
      .msg_text
        color #999
        font-size 12px
        line-height 20px
        text-overflow: ellipsis
        overflow: hidden
        white-space: nowrap
      .icon-wenjianjia
        font-size 20px
        color #222
        cursor pointer
      .icon-xiaoxi
        font-size 20px
        color #222
        margin-left 20px
        cursor pointer
    .msgcontainer
      height: calc(100% - 238px);
      background: #f3f3f3;
      padding 10px
      box-sizing border-box
      overflow-y: auto
      &::-webkit-scrollbar
        display: none;/*隐藏滚动条*/
    .chat_bottom
      height: 180px;
      display: flex
      flex-direction: column
      padding 0 10px
      .img_box
        padding:10px 10px;
        display: flex
        align-items: center
        border-top 1px solid #ddd
        position relative
        .iconfont
          font-size 22px
          margin-right 20px
          cursor pointer
        .icon-biaoqing_xiao_o,.icon-shipin
          font-size 30px
        .icon-shipin1
          font-size 26px
        .smile_box
          position: absolute
          left: 0
          bottom 54px
          width: 500px
          background #fff
          border 1px solid #eee
          padding 10px
          img
            width: 24px
            margin 5px
            cursor pointer
      .textarea
        width: 100%;
        border:none;
        outline: none;
        flex:1;
        min-height: 0;
        resize: none;
        background: transparent;
        padding:0 10px;
        box-sizing: border-box;
      .btn_box
        padding:20px;
        display: flex
        align-items: center
        justify-content: flex-end
        .btn
          width 100px
          line-height: 30px
          color:#fff;
          background: $theme-color;
          border-radius: 4px;
          text-align: center
          font-size 14px
          cursor pointer
    .chat_item{
      margin-bottom: 20px;
    }
    .starttime{
      text-align: center;
      font-size: 14px;
      line-height: 30px;
    }
    .chat_item_info{
      display: flex;
    }
    .chat_item .name{
      font-size: 14px;
      margin-bottom: 4px;
    }
    .chat_item .avatar{
      font-size: 16px;
      width: 36px;
      height: 36px;
      line-height: 36px;
      background: white;
      border-radius: 4px
      text-align: center;
      font-size 14px
    }
    .chat_item .content{
      background: #fff;
      border-radius: 5px;
      padding:11px;
      font-size: 14px;
      display: inline-block;
    }
    .content img{
      max-width: 300px;
    }
    .chat_item_info.right{
      flex-direction:row-reverse;
    }
    .chat_item_info.left .avatar{
      margin:0 15px 0 0;
    }
    .chat_item_info.right .avatar{
      margin:0 0 0 15px;
    }
    .chat_item_info.right .name{
      text-align: right;
    }
    .chat_item_info.right .content{
      background: $theme-color;
      color:#fff;
      float: right;
    }
    .file_content{
      display: flex!important;
      align-items: center;
      cursor: pointer;
    }
    .file_content p{
      flex:1;
      min-width: 0;
      margin:0 10px 0 0;
      font-size: 18px;
      word-break: break-all;
      word-wrap: break-word;
    }
    .file_content img{
      width: 30px;
      height: 30px;
      flex-shrink: 0;
    }
</style>